package handler

import (
	"app-box/api_error"
	"app-box/config"
	"app-box/middleware"
	"app-box/models"
	"app-box/service"
	"errors"
	"mime/multipart"
	"net/http"

	"github.com/gin-gonic/gin"
)

type FileHandler struct {
}

func (h FileHandler) InitRoute(router gin.IRouter) {

	router.POST("upload", middleware.RequireLogin(models.UserTypeAll), H(h.UploadFile))
	router.StaticFS("", http.Dir(config.LocalFile.FilaSavePath))

}

// 所有上传的文件默认会先放到临时文件目录，当用户提交带有临时目录文件的URL的数据时服务器会将其拷贝到永久目录，临时目录的文件1天后会自动删除
func (h FileHandler) UploadFile(ctx Context) {
	var form struct {
		File      multipart.FileHeader
		Key       string `binding:"required"` // 保存到服务器的文件名
		MD5       string `binding:"required"` // 文件MD5校验值
		Overwrite bool   // 如果冲突，是否强制覆盖
	}

	ctx.ShouldBindOrPanic(&form)
	if form.File.Size == 0 {
		panic(api_error.InvalidParameters(errors.New("文件大小为0")))
	}
	ID := ctx.GetTokenOrPanic().ID
	service := new(service.FileService)
	fileUrl := service.UploadFile(ID, form.Key, form.MD5, form.Overwrite, form.File)
	ctx.Response(map[string]interface{}{
		"Url": fileUrl,
	})
}
